package com.chen.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 每次请求过滤器——用于获取请求头的token
 * 需配置到SpringSecurity当中
 */
@Component
//注意：@ControllerAdvice注释的全局异常可以捕获Controller层和Interceptor，但是不能捕获Filter,所以Filter要自己处理
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private HandlerExceptionResolver handlerExceptionResolver;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //...
        //解析token，获取用户信息
        LoginUser loginUser = new LoginUser();
        User user = new User();
        ArrayList<SimpleGrantedAuthority> roles = new ArrayList<>();
        roles.add(new SimpleGrantedAuthority("ROLE_USER"));
        roles.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        ArrayList<SimpleGrantedAuthority> perms = new ArrayList<>();
        perms.add(new SimpleGrantedAuthority("article::add"));
        perms.add(new SimpleGrantedAuthority("article::delete"));
        perms.add(new SimpleGrantedAuthority("article::update"));
        perms.add(new SimpleGrantedAuthority("article::list"));
        user.setId(1L).setUsername("1349632732").setPassword("123456").setRoles(roles).setPerms(perms);
        loginUser.setUser(user);

        //当前线程存储用户信息
        BaseContextUtil.setLoginUser(loginUser);
        doFilter(request,response,filterChain);
    }
}
